<template>
  <div class="flex flex-col gap-2 w-full">
    <div v-for="el in computedList" :key="el.id">
      <AtomContactListCard
        :id="el.id"
        :city-en="el.cityEn"
        :city-ru="el.cityRu"
        :first-name-en="el.firstNameEn"
        :first-name-ru="el.firstNameRu"
        :last-name-en="el.lastNameEn"
        :last-name-ru="el.lastNameRu"
        :org-name-en="el.orgNameEn"
        :org-name-ru="el.orgNameRu"
        :position-name-en="el.positionNameEn"
        :position-name-ru="el.positionNameRu"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { useFilterStore } from '~/stores/filterStore'

interface Props {
  contactList: {
    id: string
    lastNameRu: string | null
    lastNameEn: string | null
    firstNameRu: string | null
    firstNameEn: string | null
    positionNameRu: string | null
    positionNameEn: string | null
    cityRu: string | null
    cityEn: string | null
    orgNameRu: string | null
    orgNameEn: string | null
  }[]
}

const props = withDefaults(defineProps<Props>(), {
  contactList: () => []
})
const { contactList } = toRefs(props)
const filterStore = useFilterStore()
const pageSize = 15
const lastPage = computed(() => Math.ceil(contactList.value.length / pageSize))
const nextPage = ref(2)

const computedList = computed(() =>
  contactList.value.slice(0, pageSize * (nextPage.value - 1))
)
window.onscroll = () => {
  if (window.innerHeight + window.pageYOffset >= document.body.offsetHeight) {
    if (nextPage.value <= lastPage.value) {
      nextPage.value += 1
    }
  }
}

watch(
  filterStore.filter,
  () => {
    nextPage.value = 2
    window.scrollTo(0, 0)
  },
  {
    deep: true
  }
)
</script>

<style scoped></style>
